<!--
  * 云喇叭表单
-->
<template>
  <a-modal title="设备测试" :width="600" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="24" v-if="verifyType == 'sn'">
          <a-form-item label="设备SN" name="sn">
            <a-input v-model:value="formData.sn" placeholder="请输入设备SN" />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="verifyType == 'message'">
          <a-form-item label="支付金额" name="message">
            <a-input v-model:value="formData.message" placeholder="请输入支付金额" />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="verifyType == 'message'" class="text-right">
          <a-button type="primary" @click="onVerify">验证</a-button>
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onNext" v-if="verifyType == 'sn'">下一步</a-button>
        <a-button type="primary" @click="onPass(2)" v-if="verifyType == 'message'">不通过</a-button>
        <a-button type="primary" @click="onPass(1)" v-if="verifyType == 'message'">通过</a-button>
        <!-- <a-button type="primary" @click="onSubmit">验证</a-button> -->
        <slot></slot>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick, computed, watch } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { smartSentry } from '/@/lib/smart-sentry'
  import { deviceApi } from '/@/api/business/b-merchant/device'
  import { useRoute } from 'vue-router'
  const route = useRoute()
  // ---------------------------- 表格列 ----------------------------
  const cloudDevice = computed(() => {
    // 0云喇叭 1云打印
    return route.path.includes('cloud-speaker') ? 0 : 1
  })

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['ok', 'update:open'])
  const visibleFlag = computed({ get: () => props.open, set: (val) => emits('update:open', val) })

  // ------------------------ 显示与隐藏 ------------------------
  function onClose() {
    Object.assign(formData.value, formDefault)
    visibleFlag.value = false
    verifyType.value = 'sn'
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  // ------------------------ 获取表单数据 ------------------------
  async function getFormData(data) {
    SmartLoading.show()
    try {
      let res = await deviceApi.findId(data)
      formData.value = { ...res.data }
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }
  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    message: undefined,
    sn: undefined,
  }

  let formData = ref({ ...formDefault })

  const rules = {
    message: [{ required: true, message: '支付金额 必填' }],
    sn: [{ required: true, message: '设备SN 必填' }],
  }

  // 点击确定，验证表单
  async function onSubmit() {
    let valid = false
    try {
      await formRef.value.validateFields()
      valid = true
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
      valid = false
    }
    return valid
  }

  const verifyType = ref('sn') // sn:设备sn,message:激活码

  // 新建、编辑API
  async function save(data) {
    SmartLoading.show()
    try {
      // let data = { ...formData.value, ...props.rowData,deviceSN: props.rowData.sn}
      // let data = {
      //   deviceSN: formData.value.sn,
      //   amount: formData.value.message,
      //   agentId: props.rowData.agentId,
      // }
      let res = await deviceApi.verify(data)
      return res
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  // 下一步
  async function onNext() {
    let valid = await onSubmit()
    if (valid) {
      save({
        deviceSN: formData.value.sn,
      }).then((res) => {
        if (res.code != 200) return
        verifyType.value = 'message'
      })
    }
  }

  // 验证金额
  async function onVerify() {
    let valid = await onSubmit()
    if (valid) {
      save({
        deviceSN: formData.value.sn,
        amount: formData.value.message,
      }).then((res) => {
        if (res.code != 200) return
        message.success('金额验证成功')
      })
    }
  }

  // 验证金额
  async function onPass(verify) {
    let valid = await onSubmit()
    if (valid) {
      save({
        deviceSN: formData.value.sn,
        verify: verify,
      })
        .then((res) => {
          if (res.code != 200) return
          let message = verify == '1' ? '通过成功' : '不通过成功'
          message.success(message)
          emits('ok')
        })
        .finally(() => {
          onClose()
        })
    }
  }

  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      if (props.open && props.rowData && props.formType != 'add') {
        getFormData(val[0])
      }
    },
    { immediate: true },
  )
</script>
